﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace QuanLyKhachHang.Forms
{
    #region using
    using QuanLyKhachHang.BUS;
    using QuanLyKhachHang.DTO;
    using QuanLyKhachHang.Utilities;
    #endregion

    public partial class frmTimKiemKH : Form
    {
        private bool blnLoading;
        private KhachHangBUS objBUS;
        private DataSet objDS;

        public frmTimKiemKH()
        {
            InitializeComponent();
        }

        public void LoadDonVi()
        {
            var objBUS = new DonViBUS(GlobalVariables.g_strConnectionString);

            try
            {
                blnLoading = true;
                objDS = objBUS.SelectAll();

                for (int i = 0; i < objDS.Tables["DonVi"].Rows.Count; i++)
                {
                    DataRow row = objDS.Tables["DonVi"].Rows[i];
                    cbxDonVi.Items.Add(new DonViDTO { MADONVI = row["MADONVI"].ToString(), TENDONVI = row["TENDONVI"].ToString() });
                }

                if (cbxDonVi.Items.Count > 0)
                    cbxDonVi.SelectedIndex = 0;
                blnLoading = false;
            }
            catch (System.Exception e)
            {
                throw new Exception(e.Message, e.InnerException);
            }
        }

        private void btnTimKiem_Click(object sender, EventArgs e)
        {
            ListViewItem objListViewItem;
            var objBUS = new KhachHangBUS(GlobalVariables.g_strConnectionString);

            try
            {
                KhachHangDTO objDto = new KhachHangDTO
                {
                    TENKH = txtTenKH.Text, 
                    MADONVI = ((DonViDTO)cbxDonVi.SelectedItem).MADONVI
                };

                objDS = objBUS.SearchKhachHang(objDto);
                lstvwDanhSachHienThi.Items.Clear();
                
                for (int i = 0; i < objDS.Tables["KhachHang"].Rows.Count; i++)
                {
                    objListViewItem = new ListViewItem();
                    DataRow row = objDS.Tables["KhachHang"].Rows[i];
                    objListViewItem.Text = row["TENKH"].ToString();
                    objListViewItem.Tag = int.Parse(row["MAKH"].ToString());
                    objListViewItem.SubItems.Add(row["DIACHI"].ToString());
                    lstvwDanhSachHienThi.Items.Add(objListViewItem);
                }
            }
            catch (System.Exception ex)
            {
                throw new Exception(ex.Message, ex.InnerException);
            }
        }

        private void frmTimKiemKH_Load(object sender, EventArgs e)
        {
            LoadDonVi();
        }
    }
}
